package com.store.app.adapter;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.store.app.R;
import com.store.app.bean.OrderSellBean;
import com.store.app.net.NetRequest;
import com.store.app.net.ifc.IOnHttpListener;
import com.store.app.utils.MoneyUtil;
import com.store.app.utils.SettingData;
import com.store.app.utils.ToastUtils;

import java.util.List;

public class OrderSellAdapter extends BaseAdapter implements IOnHttpListener {
    private List<OrderSellBean> goodsList;
    private Context context;
    private RefreshUI refreshUI;
    ViewHolder viewHolder = null;

    public OrderSellAdapter(List<OrderSellBean> goodsList, Context context,RefreshUI refreshUI) {
        this.goodsList = goodsList;
        this.context = context;
        this.refreshUI = refreshUI;
    }

    @Override
    public int getCount() {
        return goodsList.size();
    }

    @Override
    public Object getItem(int position) {

        return goodsList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {

        final OrderSellBean orderSellBean = goodsList.get(position);
//        Log.v("zyl", "适配器遍历");
        if (convertView == null) {
            viewHolder = new ViewHolder();
            convertView = LayoutInflater.from(context).inflate(R.layout.item_sell_order, null);
            viewHolder.tv_order_number = (TextView) convertView.findViewById(R.id.tv_order_number);
            viewHolder.tv_order_state = (TextView) convertView.findViewById(R.id.tv_order_state);
            viewHolder.tv_buyzer_name = (TextView) convertView.findViewById(R.id.tv_buyzer_name);
            viewHolder.tv_buyzer_phone = (TextView) convertView.findViewById(R.id.tv_buyzer_phone);
            viewHolder.tv_location = (TextView) convertView.findViewById(R.id.tv_location);
            viewHolder.tv_cancel = (TextView) convertView.findViewById(R.id.tv_cancel);
            viewHolder.tv_send_goods = (TextView) convertView.findViewById(R.id.tv_send_goods);
            viewHolder.ll_delete = (LinearLayout) convertView.findViewById(R.id.ll_delete);
            viewHolder.ll_three = (RelativeLayout) convertView.findViewById(R.id.ll_three);
            viewHolder.tv_delete = (TextView) convertView.findViewById(R.id.tv_delete);
            viewHolder.lvGoods  = (ListView) convertView.findViewById(R.id.lv_goods);
            viewHolder.tv_date  = (TextView) convertView.findViewById(R.id.tv_date);
            viewHolder.tv_all_count  = (TextView) convertView.findViewById(R.id.tv_all_count);
            viewHolder.tv_all_price  = (TextView) convertView.findViewById(R.id.tv_all_price);
            viewHolder.ll_location  = (LinearLayout) convertView.findViewById(R.id.ll_location);
            viewHolder.tv_icon_coupon  = (TextView) convertView.findViewById(R.id.tv_icon_coupon);
            viewHolder.tv_message = (TextView) convertView.findViewById(R.id.order_message);
            viewHolder.tv_loaded_code = (TextView) convertView.findViewById(R.id.tv_loaded_code);
            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }
        viewHolder.lvGoods.setFocusable(false);
        viewHolder.lvGoods.setEnabled(false);
        viewHolder.lvGoods.setClickable(false);


        String remark  = orderSellBean.getRemark();
        if(TextUtils.isEmpty(remark)){
            viewHolder.tv_message.setVisibility(View.GONE);
        }else{
            viewHolder.tv_message.setVisibility(View.VISIBLE);
            viewHolder.tv_message.setText("留言 : "+remark);
        }

//        viewHolder.tv_message.setText("订单留言 : "+orderSellBean.getRemark());
        viewHolder.tv_order_number.setText(orderSellBean.getOrder_no());
        String status = orderSellBean.getOrder_status();
        final String type = orderSellBean.getType();
        //1代表便利店商品 2代表礼券兑换
        if("1".equals(type)){
            if(status.equals(SettingData.PC__ORDER_CANCELLED)){
                status = "已取消";
                viewHolder.ll_three.setVisibility(View.GONE);
            }else if(status.equals(SettingData.PC__ASSIGEND)){
                status = "已派工";
                viewHolder.ll_three.setVisibility(View.GONE);
            }else if(status.equals(SettingData.PC__ORDER_CLOSED)){
                status = "订单完成";
                viewHolder.ll_three.setVisibility(View.GONE);
            }else if(status.equals(SettingData.PC__ORDER_PAYED)){
                status = "已支付";
                viewHolder.ll_three.setVisibility(View.VISIBLE);
                viewHolder.tv_cancel.setVisibility(View.VISIBLE);
                viewHolder.tv_send_goods.setVisibility(View.VISIBLE);
            }
            else if(status.equals(SettingData.PC__ORDER_RECEIVED)){
                status = "已收货";
                viewHolder.ll_three.setVisibility(View.GONE);
            }
            else if(status.equals(SettingData.PC_ORDER_DELIVERED)){
                status = "已发货";
                viewHolder.ll_three.setVisibility(View.GONE);
            }else{}
            //显示收货地址
            viewHolder.ll_location.setVisibility(View.VISIBLE);
            viewHolder.tv_location.setText(orderSellBean.getDelivery_address());
            viewHolder.tv_icon_coupon.setVisibility(View.VISIBLE);
            if(TextUtils.isEmpty(orderSellBean.getRebate_fee())){
                viewHolder.tv_all_price.setText(orderSellBean.getAllPrice());
            }else{
                String str  =  orderSellBean.getRebate_fee();
                if(str.equals("0.00")|str.equals("0")){
                    viewHolder.tv_all_price.setText(orderSellBean.getAllPrice());
                }else{
                    viewHolder.tv_all_price.setText(orderSellBean.getAllPrice()+"  返 ¥"+orderSellBean.getRebate_fee());
                }
            }

//            viewHolder.tv_all_price.setTextColor(Color.parseColor("#ff4242"));
        }else if("2".equals(type)){
            if(status.equals(SettingData.PC__ORDER_CANCELLED)){
                status = "已取消";
                viewHolder.ll_three.setVisibility(View.GONE);
            }else if(status.equals(SettingData.PC__ORDER_CLOSED)){
                status = "订单完成";
                viewHolder.ll_three.setVisibility(View.GONE);
            }else if(status.equals(SettingData.PC__ORDER_PAYED)){
                status = "已支付";
                viewHolder.ll_three.setVisibility(View.VISIBLE);
                viewHolder.tv_cancel.setVisibility(View.VISIBLE);
                viewHolder.tv_send_goods.setVisibility(View.GONE);
            }
            else if(status.equals(SettingData.PC__ORDER_RECEIVED)){
                status = "已收货";
                viewHolder.ll_three.setVisibility(View.GONE);
            }
            else if(status.equals(SettingData.PC_ORDER_DELIVERED)){
                status = "已发货";
                viewHolder.ll_three.setVisibility(View.VISIBLE);
                viewHolder.tv_send_goods.setVisibility(View.GONE);
                viewHolder.tv_cancel.setVisibility(View.GONE);
            }else{}
            //不显示收货地址
            viewHolder.ll_location.setVisibility(View.GONE);
            viewHolder.tv_icon_coupon.setVisibility(View.GONE);
            try {
                String str = MoneyUtil.moneyMul(orderSellBean.getAllPrice(), "10");
                str = str.split("\\.")[0];
                viewHolder.tv_all_price.setText(str + "礼券");
            }catch (Exception e){
                viewHolder.tv_all_price.setText(MoneyUtil.moneyMul(orderSellBean.getAllPrice(), "10") + "礼券");
            }
            viewHolder.tv_all_price.setTextColor(Color.parseColor("#f98116"));
        }

        viewHolder.tv_order_state.setText(status);
        viewHolder.tv_buyzer_name.setText(orderSellBean.getContact_person());
        viewHolder.tv_buyzer_phone.setText(orderSellBean.getContact_tel());

//        Log.v("zyl", "传递之前的大小：" + orderSellBean.getOrderSellGoodsBeanList().size());
        SellGoodsAdapter temAdapter = new SellGoodsAdapter(orderSellBean.getOrderSellGoodsBeanList(), context);
        viewHolder.lvGoods.setAdapter(temAdapter);
        setListViewHeightBasedOnChildren(viewHolder.lvGoods);
        viewHolder.tv_date.setText(orderSellBean.getOrder_date());
//        Log.v("zyl","商品数量："+orderSellBean.getAllCount());
        viewHolder.tv_all_count.setText(orderSellBean.getAllCount());


        viewHolder.tv_send_goods.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                Toast.makeText(context, "发货：" + position, Toast.LENGTH_LONG).show();
                AlertDialog.Builder builder = new AlertDialog.Builder(context);
                builder.
                        setMessage("请再次确认您发的货跟订单一致,并能准确送达目的地。")
                        .setNegativeButton("取消", null);

                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
//                        //用intent启动拨打电话
//                        Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + goodsList.get(position).getGoods_contact_tel()));
//                        context.startActivity(intent);
                        NetRequest netRequest = new NetRequest(OrderSellAdapter.this,context);
                        Log.v("zyl","orderSellBean.getOrder_id():"+orderSellBean.getOrder_id());
                        netRequest.requestOrderDeliver(1,orderSellBean.getOrder_id());
                    }
                });
                builder.show();
            }
        });
        viewHolder.tv_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

//                Toast.makeText(context,"取消："+position, Toast.LENGTH_LONG).show();
                String name = goodsList.get(position).getContact_person();
                if (TextUtils.isEmpty(name)) {
                    name = "";
                }
                String tel = goodsList.get(position).getContact_tel();
                if (TextUtils.isEmpty(tel)) {
                    tel = "";
                }
                AlertDialog.Builder builder = new AlertDialog.Builder(context);
                if("1".equals(type)){
                    builder.
                            setMessage("确定取消订单?")
                            .setNegativeButton("取消", null);
                }else{
                    builder.
                            setMessage("取消兑换,礼券将退还给会员")
                            .setNegativeButton("取消", null);
                }
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        NetRequest netRequest = new NetRequest(OrderSellAdapter.this, context);
                        if ("1".equals(type)) {
//                            Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + goodsList.get(position).getContact_tel()));
//                            context.startActivity(intent);
                            netRequest.requestOrderCancel(2, orderSellBean.getOrder_id());
                        } else if ("2".equals(type)) {
                            netRequest.requestLeOrderCancel(3, orderSellBean.getOrder_id());
                        }

                    }
                });
                builder.show();
            }
        });

        if(TextUtils.isEmpty(orderSellBean.getLoaded_code())){
            viewHolder.tv_loaded_code.setVisibility(View.GONE);
        }else{
            viewHolder.tv_loaded_code.setVisibility(View.VISIBLE);
            viewHolder.tv_loaded_code.setText("提货码 : "+orderSellBean.getLoaded_code());
        }
        return convertView;
    }

    public static void setListViewHeightBasedOnChildren(ListView listView) {
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            // pre-condition
            return;
        }

        int totalHeight = 0;
        for (int i = 0; i < listAdapter.getCount(); i++) {
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        listView.setLayoutParams(params);
    }

    @Override
    public void onAfinalFail() {

    }

    @Override
    public void onExecuteSuccess(int requestId, String result, String msg) {
        Log.v("zyl","回调成功 onExecuteSuccess");
            if(refreshUI!=null){
                refreshUI.refreshUI();
            }
    }

    @Override
    public void onExecuteFail(int requestId, String msg) {
        Log.v("zyl","回调成功 onExecuteFail");
        ToastUtils.showTextToast(context,msg);
    }
    public interface RefreshUI {
        void refreshUI();
    }

    class ViewHolder {
       private TextView tv_order_number;//订单号
       private TextView tv_order_state;//订单状态
       private TextView tv_buyzer_name;//买家姓名
       private TextView tv_buyzer_phone;//买家电话
       private TextView tv_location;//买家地址
        private TextView tv_date;//日期
       private TextView tv_cancel;//取消
       private TextView tv_send_goods;//发货
       private LinearLayout ll_delete;//删除线性布局
       private RelativeLayout ll_three;//三个按钮线性布局
        private TextView tv_delete;//删除
        private ListView lvGoods;//商品列表
        private TextView tv_all_count;//总数量
        private TextView tv_all_price;//总价格
        private LinearLayout ll_location;//地址布局
        private TextView tv_icon_coupon;//人民币符号
        private TextView tv_message;//订单留言
        private TextView tv_loaded_code;//提货码
    }

    DisplayImageOptions options = new DisplayImageOptions.Builder()
            .cacheInMemory(true)
            .showImageOnLoading(R.drawable.default_picture_s)
            .showImageOnFail(R.drawable.default_picture_s)
            .showStubImage(R.drawable.default_picture_s)
            .imageScaleType(ImageScaleType.EXACTLY)
            .bitmapConfig(Bitmap.Config.RGB_565)
            .build();
}
